class Solution(object):
    def maxNumber(self, nums1, nums2, k):

        def maxNumber(nums, k):
            '''
            max number of k digits from one array of same relative order
            '''
            result = []
            while k > 0:
                leading = len(nums) - k + 1
                maxValue = -1
                maxIndex = -1
                for i in range(min(len(nums), leading)):
                    if nums[i] > maxValue:
                        maxValue = nums[i]
                        maxIndex = i
                result.append(maxValue)
                nums = nums[maxIndex+1:]
                k = k - 1
            return result
        
        def merge(a, b):
            '''
            max number with all digits from a or b with same relative order
            '''
            return [max(a, b).pop(0) for _ in range(len(a) + len(b))]

        return max( [merge(maxNumber(nums1, i), maxNumber(nums2, k-i)) for i in range(0, k+1) if i <= len(nums1) and k-i <= len(nums2)] )

s = Solution()
print(s.maxNumber([6,7],[6,0,4],5))